import type { MenuType } from '@/api/system/menu'
import { cloneDeep } from 'lodash-es'
import { SystemMenuTypeEnum } from '@/enums/systemEnums'

interface MenuButtonType extends MenuType {
  disabled: boolean
}

export interface MenuPermitType extends MenuType {
  isIndeterminate: boolean
  checkedAll: boolean
  checkedList?: number[]
  buttonList?: MenuButtonType[]
}

export interface MenuTreeType extends MenuPermitType {
  children: MenuTreeType[]
}

// 菜单数据中的按钮层数据过滤作为菜单层的权限列表使用
export const filterPermitButtonFromMenu = (data: MenuType[]) => {
  const { t } = useI18n() // 国际化
  const result = cloneDeep(data)
  const permitList = result.filter(item => item.type === SystemMenuTypeEnum.BUTTON).map(item => ({ ...item, disabled: false }))
  const menuList: MenuPermitType[] = result.filter(item => item.type !== SystemMenuTypeEnum.BUTTON).map(item => ({ ...item, buttonList: [], isIndeterminate: false, checkedAll: false, checkedList: [] }))
  menuList.forEach((item: MenuPermitType) => {
    if (item.type === SystemMenuTypeEnum.MENU) {
      item.buttonList = permitList.filter(v => v.parentId === item.id)
      const viewButton = cloneDeep(permitList[0])
      viewButton.id = item.id
      viewButton.parentId = item.id
      viewButton.title = t('action', 'view')
      viewButton.sort = 0
      viewButton.permit = item.permit
      item.buttonList.splice(0, 0, viewButton)
    }
  })
  return menuList
}

// 计算菜单权限表格的权限列最小宽度
export const computedMinWidth = (data: MenuPermitType[], permit: number[]) => {
  const checkedParentIdList: number[] = []
  let minWidth = 0
  data.forEach((item: MenuPermitType) => {
    item.isIndeterminate = false
    item.checkedAll = false
    if (item.type === SystemMenuTypeEnum.MENU) {
      item.checkedList = []
      const textArr: string[] = []
      item.buttonList?.forEach(current => {
        current.disabled = false
        textArr.push(current.title)
        if (permit && permit.length > 0) {
          permit.forEach(v => {
            if (v === current.id) {
              item.checkedList?.push(v)
            }
          })
        }
      })
      if (item.checkedList.length === 0) {
        item.isIndeterminate = false
        item.checkedAll = false
      } else if (item.checkedList.length === item.buttonList?.length) {
        item.isIndeterminate = false
        item.checkedAll = true
      } else {
        item.isIndeterminate = true
        item.checkedAll = false
      }
      checkedParentIdList.push(item.parentId)
      const itemWidth = getTextWidth(textArr.join(''))
      const otherWidth = (22 + 30) * item.buttonList!.length + 24 + 8
      if (itemWidth + otherWidth > minWidth) {
        minWidth = itemWidth + otherWidth
      }
    }
  })
  return {
    minWidth,
    checkedParentIdList
  }
}

// 获取文本宽度
export const getTextWidth = text => {
  const span = document.createElement('span')
  span.style.visibility = 'hidden'
  span.style.position = 'absolute'
  span.style.top = '-9999px'
  span.style.whiteSpace = 'nowrap'
  span.style.fontSize = '18px'
  span.innerText = text
  document.body.appendChild(span)
  const width = span.offsetWidth
  document.body.removeChild(span)
  return width
}

/**
 * 树结构数据清空children是空的项（逆向递归）
 * @param data 树结构数据
 * @param pid 父级id
 */
export const recursionSetCheckboxStatus = (data: MenuTreeType[], parentId: number) => {
  data.forEach(item => {
    if (item.id === parentId) {
      if (item.type === SystemMenuTypeEnum.MENU) {
        const res = setCheckboxStatus(item.children)
        if (item.checkedList!.length === item.buttonList!.length) {
          if (res.checkedAll) {
            item.checkedAll = true
            item.isIndeterminate = false
          } else {
            item.checkedAll = false
            item.isIndeterminate = true
          }
        } else {
          if (res.checkedAll) {
            item.checkedAll = false
            item.isIndeterminate = true
          } else {
            if (res.isIndeterminate) {
              item.checkedAll = false
              item.isIndeterminate = true
            } else {
              item.checkedAll = false
              item.isIndeterminate = false
            }
          }
        }
      } else {
        const res = setCheckboxStatus(item.children)
        item.checkedAll = res.checkedAll
        item.isIndeterminate = res.isIndeterminate
        recursionSetCheckboxStatus(data, item.parentId)
      }
    } else {
      if (item.children && item.children.length > 0) {
        recursionSetCheckboxStatus(item.children, parentId)
      }
    }
  })
}

/**
 * 逆向递归处理空children的逻辑
 * @param data 树结构数据（children）
 * @param item 父级数据
 */
export const setCheckboxStatus = (data: MenuTreeType[]) => {
  const some = data.some(v => v.isIndeterminate)
  const allCheck = data.every(v => v.checkedAll)
  const allUnCheck = data.every(v => !v.checkedAll)
  let isIndeterminate = false
  let checkedAll = false
  if (some || (!some && !allCheck && !allUnCheck)) {
    isIndeterminate = true
    checkedAll = false
  } else {
    isIndeterminate = false
    if (allCheck) {
      checkedAll = true
    } else {
      checkedAll = false
    }
  }
  return {
    isIndeterminate,
    checkedAll
  }
}
